﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tilver.Configuration;
using Tilver.Configuration.Logging;

namespace Tilver.Common
{
    internal class AppenderFactory
    {
        private static Dictionary<string, Func<object>> _customBuilderCache = new Dictionary<string, Func<object>>();
        private static object _syncLock = new object();

        public static IAppender Create(string appenderName)
        {
            IAppender ret = null;
            LoggingConfigElement config = TilverSection.GetSection().LoggingConfig;
            if (config.FileAppenders[appenderName] != null)
            {
                ret = new FileAppender(config.FileAppenders[appenderName]);
            }
            if (ret == null)
            {
                throw new ArgumentOutOfRangeException("appenderName", "不存在此appenderName。");
            }
            return ret;
        }
        private static Func<object> GetBuilder(string typeName)
        {
            if (!_customBuilderCache.ContainsKey(typeName))
            {
                lock (_syncLock)
                {
                    if (!_customBuilderCache.ContainsKey(typeName))
                    {
                        Type type = Type.GetType(typeName);
                        var builder = DynamicCompiler.CreateBuilder(type, true);
                        _customBuilderCache.Add(typeName, builder);
                    }
                }
            }
            return _customBuilderCache[typeName];
        }
    }
}
